package com.news.activity;

import com.xiang.news.R;
import com.news.contant.PackageContent;
import com.news.db.DBUtil;
import com.news.db.info.ContentInfo;
import com.news.util.NetUtil;
import com.rss.data.RssItem;
import com.umeng.socialize.controller.RequestType;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.GestureDetector.OnGestureListener;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.widget.ImageView;
import android.widget.TextView;

public class ContentDetailActivity extends Activity implements OnClickListener,
		OnGestureListener {
	private String content_URL = "http://news.sina.com.cn/s/2013-02-22/144626331024.shtml";
	public static String tittle = "标题";
	public static String pubDate = "00:00:00";

	private String startTag = "<!-- 正文内容 begin -->"; // 内容开始标签
	private String endTag = "<!-- publish_helper_end -->";// 内容结束标签

	private WebView webview_showContent;// 显示正文的WebView
	private TextView txv_tittle;// 文章标题
	private TextView txv_pubDate; // 发布时间
	private ImageView img_back;// 返回键
	private ImageView img_share;// 分享键
	private ImageView img_comment;// 评论

	public static String content;// 正文内容

	GestureDetector detector;

	private DBUtil dbUtil;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.content_detail_layout);

		detector = new GestureDetector(this);

		initData();

		webview_showContent = (WebView) findViewById(R.id.content_detail_webview_show_content);
		txv_tittle = (TextView) findViewById(R.id.content_detail_txv_tittle);
		txv_pubDate = (TextView) findViewById(R.id.content_detail_txv_pubdate);
		img_back = (ImageView) findViewById(R.id.content_detail_back);
		img_share = (ImageView) findViewById(R.id.content_detail_share);
		img_comment = (ImageView) findViewById(R.id.content_detail_comment);

		img_back.setOnClickListener(this);
		img_share.setOnClickListener(this);
		img_comment.setOnClickListener(this);

		webview_showContent.getSettings().setJavaScriptEnabled(true);
		webview_showContent.getSettings().setLayoutAlgorithm(
				LayoutAlgorithm.SINGLE_COLUMN);
		webview_showContent.getSettings().setSupportZoom(false);
		webview_showContent.getSettings().setBuiltInZoomControls(false);// 去掉放大缩小按钮
		webview_showContent.getSettings().setUseWideViewPort(false);
		webview_showContent.getSettings().setLoadWithOverviewMode(true);
		webview_showContent.getSettings().setLoadWithOverviewMode(true);

		webview_showContent.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);// 设置滚动条的显示位置（在webview内还是外）

		// 从文章列表传过来的文章内容是否为空，否则先去查询数据库。是则直接显示
		if (content == null || content.equals("")) {
			content = qurryContentByUrl();
		}

		if (content == null || content.equals("")) {
			getPageCode();
		} else {
			showContent(content);
		}

		txv_tittle.setText(tittle);
		txv_pubDate.setText(pubDate);

	}

	private void getPageCode() {
		// try {
		// content = NetUtil.GetHtml(content_URL);
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// showContent(content);

		PageTask task = new PageTask();
		task.execute(content_URL);
	}

	private void showContent(String content) {
		if (content != null) {
			int starIndex = content.indexOf(startTag);
			int endIndex = content.indexOf(endTag);
			if (starIndex > 0 && endIndex > starIndex) {
				content = content.substring(starIndex, endIndex);
			}
		} else {
			content = "    Content loading error……";
		}

		// ImgFliter.fliter(content);//过滤图片地址
		PackageContent.setFont(this);
		content = PackageContent.packingContent(content, setPadding());// 组装文字内容

		webview_showContent.loadDataWithBaseURL("", content, "text/html",
				"utf-8", "");

	}

	private void initData() {
		Bundle bundle = getIntent().getBundleExtra("RssFeed");
		content_URL = bundle.getString(RssItem.LINK);
		tittle = bundle.getString(RssItem.TITLE);
		pubDate = bundle.getString(RssItem.PUBDATE);

		content = bundle.getString(ContentInfo.CONTENT);

		startTag = bundle.getString("startTag");
		endTag = bundle.getString("endTag");
	}

	/**
	 * 下载网页源代码
	 */
	class PageTask extends AsyncTask<String, Integer, String> {

		// 可变长的输入参数，与AsyncTask.exucute()对应
		@Override
		protected String doInBackground(String... params) {
			try {
				content = NetUtil.GetHtml(content_URL);
				return content;
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(String result) {
			// 返回HTML页面的内容
			showContent(result);
			/**
			 * 向数据库插入文章内容
			 */
			final String _content = result;
			new Thread() {
				public void run() {
					insertContent(content_URL, _content);
				};
			}.start();
		}

		@Override
		protected void onPreExecute() {
			// 任务启动，可以在这里显示一个对话框，这里简单处理
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// 更新进度
		}
	}

	private int setPadding() {
		int padding = 0;
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		System.out.println("screem:" + dm.widthPixels + "x" + dm.heightPixels);
		if (dm.widthPixels <= 320) {
			padding = 6;
		} else if (dm.widthPixels > 320 || dm.widthPixels <= 480) {
			padding = 10;
		} else if (dm.widthPixels > 480 || dm.widthPixels <= 800) {
			padding = 13;
		}
		return padding;

	}

	@Override
	public void onClick(View v) {
		int vid = v.getId();
		switch (vid) {
		case R.id.content_detail_back:// 返回
			this.finish();
			overridePendingTransition(R.anim.left_in, R.anim.right_out);
			break;
		case R.id.content_detail_share:// 分享
			// UMSocialService controller =
			// UMServiceFactory.getUMSocialService("NEWS", RequestType.SOCIAL);
			// controller.openShare( this ,false);
			// overridePendingTransition(R.anim.right_in, R.anim.left_out);
			
			UMSocialService controller = UMServiceFactory.getUMSocialService("NEWS", RequestType.SOCIAL);
			//设置默认分享文字
			controller.setShareContent("**美文分享**：《"+tittle+"》    "+content_URL);
			controller.openShare( this,false);
			
			break;
		case R.id.content_detail_comment:// 评论
//			 UMSocialService controller01 =
//			 UMServiceFactory.getUMSocialService("NEWS", RequestType.SOCIAL);
//			 controller01.openComment( this ,false);
			 
			// overridePendingTransition(R.anim.right_in, R.anim.left_out);
			break;

		default:
			break;
		}
	}

	@Override
	public boolean onDown(MotionEvent e) {
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		if (e2.getX() - e1.getX() > 100 && Math.abs(velocityX) > 0) {
			if (Math.abs(e2.getY() - e1.getY()) < 50) {
				this.finish();
				overridePendingTransition(R.anim.left_in, R.anim.right_out);
			}
		}
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {

	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if (this.detector.onTouchEvent(ev)) {
			return true;
		}
		return super.dispatchTouchEvent(ev);
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {

	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		return false;
	}

	@Override
	public void onBackPressed() {
		this.finish();
		overridePendingTransition(R.anim.left_in, R.anim.right_out);
		super.onBackPressed();
	}

	/**
	 * 向数据库插入文章内容
	 */
	private void insertContent(String content_URL, String content) {
		if (dbUtil == null) {
			dbUtil = new DBUtil(this);
		}
		dbUtil.updateContent(content_URL, content);
	}

	/**
	 * 从数据库获取文章内容
	 */
	private String qurryContentByUrl() {
		if (dbUtil == null) {
			dbUtil = new DBUtil(this);
		}
		return dbUtil.qurryContentByUrl(content_URL);
	}
}
